<?php
namespace app\admin\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\Floor as FloorModel;
use app\common\model\Type as TypeModel;
use app\common\model\User as UserModel;
use app\common\model\Unit as UnitModel;
use app\common\model\Spec as SpecModel;
use app\common\controller\AdminBase;
use app\common\model\User;
use think\Cache;
use think\Db;

/**
 * 商品管理
 * Class Article
 * @package app\admin\controller
 */
class Goods extends AdminBase
{
    protected $goods_model;
    protected $floor_model;
    protected $user_model;
    protected $unit_model;
    protected $spec_model;
    protected $type_model;
    protected function _initialize()
        {
        parent::_initialize();
        $this->goods_model  = new GoodsModel();
        $this->floor_model = new FloorModel();
        $this->user_model = new UserModel();
        $this->unit_model = new UnitModel();
        $this->spec_model = new SpecModel();
        $this->type_model = new TypeModel();
        $category_level_list = $this->floor_model->getLevelList();
        $this->assign('category_level_list', $category_level_list);

        $getFloor = $this->floor_model->getFloor();
        $this->assign('getFloor', $getFloor);

        //查询缓存权限值
        $identity_list_info = Cache::get('identity_list_info');
        $this->assign('identity_list_info',$identity_list_info);
    }

    /**
     * 规格管理列表
     */
    public function index()
    {
        $where = [];
        $params = input();
        if (isset($params['fid'])){
            if ($params['fid'] != '请选择'){
                $where= ['g.fid' => $params['fid']];
            }
        }
        $goods_list = $this->goods_model->index($where);
        return $this->fetch('index', ['goods_list' => $goods_list]);
    }



    /**
     * 添加商品
     * @return mixed
     */
    public function add()
    {
        return $this->fetch();
    }

    /**
     * 保存商品
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Goods');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $data['create_time'] = time();
                $data['update_time'] = time();
                if ($data['fid'] == '请选择'){
                    $this->error('请选择分类');
                }
                if ($this->goods_model->allowField(true)->save($data)) {

                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }
    }

    /**
     * 编辑商品
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $article = $this->goods_model->find($id);
//        $list = $this->type_model->getTypeForFloor($article['fid']);
        return $this->fetch('edit', ['article' => $article]);
    }


    /**
     * 商品详情
     * @param $id
     * @return mixed
     */
    public function detaile($id)
    {
        $goods = $this->goods_model->find($id);
        $user = $this->user_model->find($goods['user_id']);
        $floor1 = $this->floor_model->find($goods['cate1_id']);
        $floor2 = $this->floor_model->find($goods['cate2_id']);
        $spec = $this->spec_model->find($goods['spec_id']);
        $unit = $this->unit_model->find($goods['unit_id']);
        $goods['photo'] = explode(';',$goods['photo']);
        $goods['ctime'] = unixToDate($goods['ctime']);
        return $this->fetch('detaile', [
            'goods' => $goods,
            'user' => $user,
            'floor1' => $floor1,
            'floor2' => $floor2,
            'spec' => $spec,
            'unit' => $unit
        ]);
    }


    /**
     * 更新商品
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            $validate_result = $this->validate($data, 'Goods');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
//                $data['keywords'] = $data['keywords']?$data['keywords']:$data['title'];
                $data['update_time'] = time();
                if ($this->goods_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }

    /**
     * 删除商品
     * @param int   $id
     * @param array $ids
     */
    public function delete($id = 0, $ids = [])
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->goods_model->where(['id'=>['in',$id]])->delete()) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('请选择需要删除的商品');
        }
    }

    /**
     * 商品审核状态切换
     * @param array  $ids
     * @param string $type 操作类型
     */
    public function toggle($ids = [], $type = '')
    {
        $data   = [];
        $status = $type == 'audit' ? 1 : 0;

        if (!empty($ids)) {
            foreach ($ids as $value) {
                $data[] = ['id' => $value, 'status' => $status];
            }
            if ($this->goods_model->saveAll($data)) {
                $this->success('操作成功');
            } else {
                $this->error('操作失败');
            }
        } else {
            $this->error('请选择需要操作的商品');
        }
    }

    /**
     * 加精置顶推荐下载状态开关
     */
    public function topToggle($id){
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            if(@$data['api'] == 1){ //判断前台请求
                $field          =   $data['field'];
                $data[$field]   =   $data['rank'];
                unset($data['field']);
                unset($data['rank']);
                unset($data['api']);
            }
            if ($this->goods_model->where(['id' => $id])->update($data) !== false) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }


    /**
     * 商品回收站
     */
    public function recovery($cate2_id = 0, $keyword = '',$page = 1){
        $map['is_del'] = 1;
        if ($cate2_id > 0) {
            $category_children_ids = $this->floor_model->where(['path' => ['like', "%,{$cate2_id},%"]])->column('id');
            $category_children_ids = (!empty($category_children_ids) && is_array($category_children_ids)) ? implode(',', $category_children_ids) . ',' . $cate2_id : $cate2_id;
            $map['cate2_id']            = ['IN', $category_children_ids];
        }

        if (!empty($keyword)) {
            $map['title'] = ['like', "%{$keyword}%"];
        }

        $list = $this->goods_model->where($map)->order(['ctime' => 'DESC'])->paginate(15, false, ['page' => $page]);
        $category_list = $this->floor_model->column('name', 'id');
        return $this->fetch('recovery',['list'=>$list , 'category_list' => $category_list, 'cate2_id' => $cate2_id, 'keyword' => $keyword]);
    }




    /**
     * 清除回收站商品
     * @param int   $id
     * @param array $ids
     */
    public function cleanUp($id = 0, $ids = [])
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->goods_model->where(['id'=>['in',$id]])->delete()) {
                $this->success('清除成功');
            } else {
                $this->error('清除失败');
            }
        } else {
            $this->error('请选择需要清除的商品');
        }
    }



    /**
     * 还原回收站商品
     * @param int   $id
     * @param array $ids
     */
    public function restore($id = 0, $ids = [])
    {
        $id = $ids ? $ids : $id;
        if ($id) {
            if ($this->goods_model->where(['id'=>['in',$id]])->update(['is_del'=>0])) {
                $this->success('还原成功');
            } else {
                $this->error('还原失败');
            }
        } else {
            $this->error('请选择需要还原的商品');
        }
    }







}